import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export interface User {
  id: string
  username: string
  email: string
  roles: string[]
  permissions: string[]
  avatar?: string
  created_at: string
  updated_at: string
}

export interface LoginForm {
  username: string
  password: string
}

export interface RegisterForm {
  username: string
  email: string
  password: string
  confirm_password: string
}

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const loading = ref(false)

  // 登录
  const login = async (form: LoginForm) => {
    loading.value = true
    try {
      const response = await axios.post('/api/auth/login', form)
      const { token: newToken, user: userData } = response.data.data
      
      token.value = newToken
      user.value = userData
      localStorage.setItem('token', newToken)
      
      // 设置axios默认header
      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
      
      return { success: true }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败' 
      }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (form: RegisterForm) => {
    loading.value = true
    try {
      const response = await axios.post('/api/auth/register', form)
      return { 
        success: true, 
        message: response.data.message || '注册成功' 
      }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '注册失败' 
      }
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) return
    
    try {
      const response = await axios.get('/api/auth/me')
      user.value = response.data.data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
    }
  }

  // 退出登录
  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    delete axios.defaults.headers.common['Authorization']
  }

  // 更新用户信息
  const updateProfile = async (data: Partial<User>) => {
    loading.value = true
    try {
      const response = await axios.put('/api/auth/profile', data)
      user.value = { ...user.value, ...response.data.data }
      return { success: true, message: '更新成功' }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '更新失败' 
      }
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (data: { old_password: string; new_password: string }) => {
    loading.value = true
    try {
      await axios.put('/api/auth/change-password', data)
      return { success: true, message: '密码修改成功' }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '密码修改失败' 
      }
    } finally {
      loading.value = false
    }
  }

  // 检查权限
  const hasPermission = (permission: string) => {
    return user.value?.permissions?.includes(permission) || false
  }

  // 检查角色
  const hasRole = (role: string) => {
    return user.value?.roles?.includes(role) || false
  }

  return {
    user,
    token,
    loading,
    login,
    register,
    getUserInfo,
    logout,
    updateProfile,
    changePassword,
    hasPermission,
    hasRole
  }
})